var nhacso = {
    init: function(){
        nhacso.injectDownloadButton();
    },
    injectDownloadButton: function(){
        var newButton = 
        $('<img class="" src="'  + chrome.extension.getURL('nhacso-icon.png')  + '"/>');
        newButton.click(function(){
            //extract the album id
            var matches = document.body.innerHTML.match(/loadXMLDoc\("\/Music\/related_album\.aspx\?ID=(\d+)/i);
            if(matches != null){
                var albumId = matches[1];
                
                $.ajax({
                    url: 'http://nhacso.net/Music/related_album.aspx',
                    data: {
                        ID: albumId
                    },
                    dataType: 'xml',
                    success: function(response){
                        var songs = [];
                        $(response).find('s').each(function(index, node){
                            
                            songs.push({
                                url: 'http://nhacso.net/Music/download.aspx?id=' + $(node).attr('si')
                            });
                        });
                        
                        var proceed = true;
                        if( songs.length > 1){
                            if( !confirm('Có nhiều tab sẽ được mở. Bạn có chắc chắn muốn download toàn bộ album khong?')){
                                proceed = false;
                            }
                        }
                        if( proceed ){
                            chrome.extension.sendRequest({
                                event: EVENT.DOWNLOAD_ALBUM,
                                songs: songs
                            });
                        }
                    },
                    asycn: true
                });
            }
            
        });
        $('#playAlbumDiv').find('td[width=110]').append(newButton);
    }
    
    
};

nhacso.init();